import time

import utils.date_util as date_util
from database.mysqlhelper import MySqLHelper
from database.trans.mysqlhelpernew import MySqLHelperNew

db = MySqLHelper()
db_new = MySqLHelperNew()

insert_sql = 'insert into  ?  VALUES (%s &) '
select_sql = 'select * from ? where f_id >=  %s and f_id < %s'
count_sql = 'select max(f_id) from ? '
count_sql1 = 'select min(f_id) from ? '
db_arr = ['t_user_info',
          't_stock_info',
          't_boards_info',
          't_funds_info',
          't_funds_info_his',
          't_monitor_result',
          't_monitor_strategy',
          't_monitor_strategy_config',
          't_stock_day_info',
          't_stock_day_k',
          't_stock_day_macd',
          't_stock_monitor',
          't_stock_month_k',
          't_stock_month_macd'
          ]
seq_num = 500


def query_interval():
    for db_name in db_arr:
        print(db_name)
        # 寻址
        sql1 = count_sql.replace('?', db_name)
        cur_num = db_new.selectone(sql1, [])
        cur_num = cur_num[0]
        max_num = db.selectone(sql1, [])[0]
        if type(max_num) is not int:
            max_num = 1000
        if type(cur_num) is not int:
            sql4 = count_sql1.replace('?', db_name)
            cur_num = db.selectone(sql4, [])[0]
            if type(cur_num) is not int:
                print("未找到数据")
                print(cur_num)
                continue
            cur_num = cur_num - 1
        while True:
            arr_select = [cur_num + 1, cur_num + 1 + seq_num]
            print(arr_select)
            sql2 = select_sql.replace('?', db_name)
            print(db_name + "开始时间" + date_util.get_time_str())
            arr_result = db.selectall(sql2, arr_select)
            print(db_name + "结束时间" + date_util.get_time_str())
            if len(arr_result) != 0:
                cur_num = cur_num + seq_num
                sql3 = insert_sql.replace('?', db_name)
                word = ''
                for i in range(len(arr_result[0]) - 1):
                    word += ', %s'
                sql3 = sql3.replace('&', word)
                count = db_new.insertmany(sql3, arr_result)
                if count != len(arr_result):
                    print(db_name + "插入数据错误")
                    print(sql3)
                    break
                #time.sleep(1)
            elif cur_num < max_num:
                print(db_name + "数据断档")
                cur_num = cur_num + seq_num
            else:
                # 数据查询完毕
                break


# 1.配置新库的参数 db_new
# 2.db_arr配置要迁移的表
# 3.执行下面方法-项目启动前执行，执行完成后再启动项目
if __name__ == '__main__':
    query_interval()
